//
//	File: Util.cpp
//
// Implement some generic features in Util.h

#include "Util.h"
#include <ctype.h>
#include <string.h>


DWORD CharToHex(const char *str)  
{  
    return strtoul(str, NULL, 16); 
}


void CharToUpper( char* str )
{
	while( *str != 0 )
	{
		if( *str >= 'a' && *str <= 'z' )
			*str = _toupper( *str );
		str++;
	}
}

void CharToLower( char* str )
{
	while( *str != 0 )
	{
		if( *str >= 'A' && *str <= 'Z' )
			*str = _tolower( *str );
		str++;
	}
}

void CharTrimLeftRight(char* str )
{
	int strLeftIdx = 0;
	int strRightIdx = strlen(str) - 1;
	char* FirstIdx = str;

	// Trim Left
	while( *str != 0 )
	{
		if( (*str != ' ') && (*str != '\n') && (*str != '\t') )
		{
			break;
		}
		strLeftIdx++;
		str++;
	}

	// Trim Right
	while(	(*(FirstIdx + strRightIdx) == ' ') ||
			(*(FirstIdx + strRightIdx) == '\n') ||
			(*(FirstIdx + strRightIdx) == '\t') )
	{
		strRightIdx--;
		if( strRightIdx == 0 )
			break;
	}

	// Get Final string
	int Idx = 0;
	for(int i = strLeftIdx; i <= strRightIdx; i++,Idx++ )
	{
		*(FirstIdx+Idx) = *(FirstIdx+i);
	}
	
	*(FirstIdx+Idx) = 0;
}

int  Char_Find_first_not_of( const char* SrcStr, const char* SubStr, int index )
{
	int StrIdx = 0;
	
	while( *(SrcStr+index+StrIdx) != 0 )
	{
		int SubStrIdx = 0;
		while( *(SubStr+SubStrIdx) != 0 )
		{
			if( *(SrcStr+index+StrIdx) == *(SubStr+SubStrIdx) )
				break;
			SubStrIdx++;
		}
		if( *(SubStr+SubStrIdx) == 0 )
			return StrIdx;
		StrIdx++;
	}
	return -1;
}

int  Char_Find_first_of( const char* SrcStr, const char SubStr, int index )
{
	int StrIdx = 0;
	
	while( *(SrcStr+index+StrIdx) != 0 )
	{
		if( *(SrcStr+index+StrIdx) == SubStr )
			return StrIdx;

		StrIdx++;
	}
	return -1;
}


int  Char_Find_last_not_of( const char* SrcStr, const char* SubStr, int str_len )
{
	str_len--;
	while(str_len >= 0)
	{
		int SubStrIdx = 0;
		while( *(SubStr+SubStrIdx) != 0 )
		{
			if( *(SrcStr+str_len) == *(SubStr+SubStrIdx) )
				break;
			SubStrIdx++;
		}
		if( *(SubStr+SubStrIdx) == 0 )
			return str_len;
		str_len--;
	}
	return -1;
}
